<template>
    <!-- 滚动区域开始 -->
    <view class="container">
        <z-paging
            ref="paging"
            :scroll-with-animation="true"
        >
            <template #top>
                <!-- 自定义导航区域开始 -->
                <TridentNavBar>
                    <template #left>
                        <!-- #ifdef MP-ALIPAY -->
                        <i class="iconfont icon-zuojiantou" style="font-size: 36rpx;font-weight: bold;"></i>
                        <!-- #else -->
                        <i class="iconfont icon-zuojiantou" style="font-size: 36rpx;"></i>
                        <!-- #endif -->
                    </template>
                    <template #default>聊天信息</template>
                    <template #right >
                        <!-- #ifdef MP-ALIPAY -->
                        <i @click="goto('/pages/index/index')" class="iconfont icon-home" style="font-size: 36rpx;font-weight: bold;"></i>
                        <!-- #else -->
                        <i @click="goto('/pages/index/index')" class="iconfont icon-home" style="font-size: 36rpx;"></i>
                        <!-- #endif -->
                    </template>
                </TridentNavBar>
                <!-- 自定义导航区域结束 -->
            </template>

            <!-- 头部信息区域开始 -->
            <view class="user-wrap" v-if="groupChat || friend">
                <!-- 骨架屏区域 -->
                <uv-skeletons :loading="isSkeleton" :skeleton="skeletons" v-if="query.mode == '1'"></uv-skeletons>
                <uv-skeletons :loading="isSkeleton" :skeleton="skeletons" v-else v-for="(index) in 5" :key="index"></uv-skeletons>

                <!-- 好友 -->
                <view class="item-box" v-if="friend">
                    <view class="avatar">
                        <image
                            :src="friend.info.avatar_url ? global.FILE_DOMAIN + friend.info.avatar_url : 'src/assets/images/default_avatar.png'"
                        />
                    </view>
                    <view class="username ellipsis-1">{{ friend.info.username }}</view>
                </view>

                <!-- 群聊成员 -->
                <view class="item-box" v-for="(item, index) in groupChat?.member" :key="index">
                    <view class="avatar">
                        <image
                            :src="item.avatar_url ? global.FILE_DOMAIN + item.avatar_url : 'src/assets/images/default_avatar.png'"
                        />
                    </view>
                    <view class="username ellipsis-1">{{ item.username }}</view>
                </view>

                <!-- 添加群成员按钮 -->
                <view class="item-box" @click="goto('/pagesFriend/contact/index?gid=' + query.gid)" v-if="query.mode == '2' && admin?.uid == userStore.profile.user?.uid">
                    <div class="top"><i class="iconfont icon-jia"></i></div>
                </view>

                <!-- 移除群成员按钮 -->
                <view class="item-box" @click="goto('/pagesGroup/member/index?gid=' + query.gid)" v-if="query.mode == '2' && admin?.uid == userStore.profile.user?.uid">
                    <view class="top"><i class="iconfont icon-jian"></i></view>
                </view>
            </view>
            <!-- 头部信息区域结束 -->

            <!-- 群聊相关面板区域开始 -->
            <view class="group-wrap" v-if="query.mode == '2'">
                <!-- 群聊名称 -->
                <view @click="popupNameRef.open('bottom')">
                    <TridentCellItem :item="{title: '群聊名称', value: groupChat?.name}" position="right"/>
                </view>

                <!-- 是否管理员 -->
                <TridentCellItem :item="{title: '管理员', value: admin?.username}" position="right" :is_arrows="false"/>

                <!-- 群二维码 -->
                <view @click="handleShowQrcode">
                    <TridentCellItem :item="{title: '群二维码'}"/>
                </view>
                
                <!-- 群公告 -->
                <view @click="goto('/pagesGroup/notice/index?gid=' + groupChat.id)">
                    <TridentCellItem :item="{title: '群公告'}"/>
                </view>
                
                <!-- 备注 -->
                <TridentCellItem :item="{title: '备注', value: groupChat?.note}" :is_arrows="false" position="right"/>


                <!-- 我在群里的用户名 -->
                <TridentCellItem :item="{title: '我在群里的用户名', value: userStore.profile.user?.username}" position="right"/>
                
                <!-- 显示群成员用户名 -->
                <!-- <TridentCellItem :item="{title: '显示群成员用户名'}"/> -->
            </view>
            <!-- 群聊相关面板区域结束 -->

            <!-- 查询聊天记录开始 -->
            <view class="search-record-wrap">
                <view v-if="query.mode == '1'" @click="goto('/pagesChat/record/index?mode=' + query.mode + '&to_uid=' + friend?.info.uid)">
                    <!-- 好友聊天记录 -->
                    <TridentCellItem :item="{title: '查询聊天记录'}"/>

                </view>
                <!-- 群聊记录聊天 -->
                <view v-else @click="goto('/pagesChat/record/index?mode=' + query.mode + '&to_uid=' + groupChat.id)">
                    <TridentCellItem :item="{title: '查询聊天记录'}"/>
                </view>
            </view>
            <!-- 查询聊天记录结束 -->

            <!-- 操作区域开始 -->
            <view class="operate-wrap">
                <!-- 消息免打扰 -->
                <view class="operate-item">
                    <view class="left">消息免打扰</view>
                    <view class="right">
                        <fui-switch
                            @change="handleDisturb"
                            :color="global.THEME_COLOR"
                            :scaleRatio="0.6"
                            :checked="isDisturb"
                        >
                            <text class="fui-switch--text">{{isDisturb?'ON':'OFF'}}</text>
                        </fui-switch>
                    </view>
                </view>

                <!-- 置顶聊天 -->
                <view class="operate-item">
                    <view class="left">置顶聊天</view>
                    <view class="right">
                        <fui-switch
                            @change="handleTop"
                            :color="global.THEME_COLOR"
                            :scaleRatio="0.6"
                            :checked="isTop"
                        >
                            <text class="fui-switch--text">{{isTop?'ON':'OFF'}}</text>
                        </fui-switch>
                    </view>
                </view>

                <!-- 提醒 -->
                <view class="operate-item">
                    <view class="left">提醒</view>
                    <view class="right">
                        <fui-switch
                            :color="global.THEME_COLOR"
                            :scaleRatio="0.6"
                            :checked="false"
                        >
                            <text class="fui-switch--text">{{false?'ON':'OFF'}}</text>
                        </fui-switch>
                    </view>
                </view>
            </view>
            <!-- 操作区域结束 -->

            <!-- 清空聊天记录开始 -->
            <view class="clear-record-wrap" @click="handleClearChatRecord">
                <TridentCellItem :item="{title: '清空聊天记录'}"/>
            </view>
            <!-- 清空聊天记录结束 -->

            <!-- 投诉区域开始 -->
            <view class="complaint-wrap">
                <TridentCellItem :item="{title: '投诉'}"/>
            </view>
            <!-- 投诉区域结束 -->

            <!-- 转让管理员区域开始 -->
            <view class="btn-wrap"
                v-if="query.mode == '2' && admin?.uid == userStore.profile.user?.uid"
                @click="popupTransferRef.open('bottom')"
            >转让管理员</view>
            <!-- 转让管理员区域结束 -->

            <!-- 解散群聊区域开始 -->
            <view class="btn-wrap"
                v-if="query.mode == '2' && admin?.uid == userStore.profile.user?.uid"
                @click="handleDissolveGroupChat"
            >解散群聊</view>
            <!-- 解散群聊区域结束 -->

            <!-- 退出群聊区域开始 -->
            <view class="btn-wrap"
                v-if="query.mode == '2' && admin?.uid != userStore.profile.user?.uid" 
                @click="handleLogoutGroupChat"
            >退出群聊</view>
            <!-- 退出群聊区域结束 -->

            <!-- 编辑群名弹层开始 -->
            <uni-popup
                ref="popupNameRef"
                type="bottom"
                background-color="#fff"
                :mask-click="false"
            >
                <view class="popup-wrap">
                    <!-- 标题区域开始 -->
                    <view class="title-box">
                        <text>编辑群名</text>
                        <i class="iconfont icon-guanbi" @click="popupNameRef.close()"></i>
                    </view>
                    <!-- 标题区域结束 -->

                    <!-- 表单区域开始 -->
                    <view class="input-box">
                        <uni-forms label-width="100">
                            <uni-forms-item label="群名">
                                <uni-easyinput type="text" :primaryColor="global.THEME_COLOR" v-model="editParams.name" placeholder="请输入群名" />
                            </uni-forms-item>
                        </uni-forms>
                    </view>
                    <!-- 表单区域结束 -->

                    <TridentButton @handleClick="handleEditName"/>
                </view>
            </uni-popup>
            <!-- 编辑群名弹层结束 -->

            <!-- 群二维码弹层开始 -->
            <uni-popup
                ref="popupQrcodeRef"
                type="bottom"
                background-color="#fff"
                :mask-click="false"
            >
                <view class="popup-wrap">
                    <!-- 标题区域开始 -->
                    <view class="title-box">
                        <text>群二维码</text>
                        <i class="iconfont icon-guanbi" @click="handleCloseQrcode"></i>
                    </view>
                    <!-- 标题区域结束 -->
                    
                    <view class="qrcode-box">
                        <uv-qrcode ref="qrcode" :hide="isHideQrcode" value="https://h5.uvui.cn"></uv-qrcode>
                    </view>
                </view>
            </uni-popup>
            <!-- 编二维码弹层结束 -->

            <!-- 转让管理员弹层开始 -->
            <uni-popup
                ref="popupTransferRef"
                type="bottom"
                background-color="#fff"
                :mask-click="false"
            >
                <view class="popup-wrap" style="padding-bottom: 0rpx;">
                    <view class="title-box">
                        <text>选择管理员</text>
                        <i class="iconfont icon-guanbi" @click="popupTransferRef.close()"></i>
                    </view>
                    
                    <view class="member-box">
                        <view class="member" v-for="(item, index) in candidateMemberList" :key="index" @click="handleCheckMember(item)">
                            <i class="iconfont icon-weixuanzhong" v-if="item.is_admin == 0"></i>
                            <i class="iconfont icon-xuanzhong" v-else></i>
                            <view class="avatar">
                                <image
                                    :src="item.avatar_url ? global.FILE_DOMAIN + item.avatar_url : 'src/assets/images/default_avatar.png'"
                                />
                            </view>

                            <view class="username">{{ item.username }}</view>
                        </view>
                    </view>
                    <view class="member-btn-box">
                        <TridentButton style="padding-top: 0rpx;" text="取 消" :width="160" :height="60" bgColor="#cdcdcd" @click="handleCancel"/>

                        <TridentButton style="padding-top: 0rpx;" text="确 认" :width="160" :height="60" @click="handleConfirm"/>
                    </view>
                </view>
            </uni-popup>
            <!-- 转让管理员弹层结束 -->

        </z-paging>
    </view>
    <!-- 滚动区域结束 -->
</template>

<script lang="ts" setup>
import { goto } from '@/utils/tools'
import { reqDissolveAPI, reqEditGroupChatAPI, reqGroupChatDetailAPI, reqGroupChatDisturbAPI, reqGroupChatTopAPI, reqRemoveMemberAPI, reqTransferAdminAPI } from '@/apis/groupChat'
import { useUserStore } from '@/stores'
import type { EditGroupChatParams, GroupChat, Member } from '@/types/groupChat'
import { inject, reactive, ref } from 'vue'
import type { Friend } from '@/types/friend'
import { onShow } from "@dcloudio/uni-app"
import { reqDisturbAPI, reqFriendDetailAPI, reqTopAPI } from '@/apis/friend'



// --------------- 定义全局变量开始 ---------------
// 全局属性
const global: any = inject('global')

// 用户存储
const userStore = useUserStore()

// 获取页面参数
const query = defineProps({
    "mode": {
        type: String,
        default: '0'
    },
    "id": {
        type: String,
        default: '0'
    },
    "gid": {
        type: String,
        default: '0'
    }
})

const paging = ref()
// --------------- 定义全局变量结束 ---------------



onShow( async () => {

    if (query.mode == '1') {
        await getFriend()
    } else {
        await getGroupChatInfo()
        editParams.value.name = groupChat.value?.name
    }
})



// --------------- 清空聊天记录开始 ---------------
const handleClearChatRecord = () => {
    uni.showModal({
        content: '确定删除聊天记录吗?',
        confirmColor: global.THEME_COLOR,
        success: (res) => {
            if (res.confirm) {
            }
        }
	})
}
// --------------- 清空聊天记录结束 ---------------



// --------------- 处理好友信息开始 ---------------
// 是否免打扰
const isDisturb = ref<boolean>(false)

// 是否置顶
const isTop = ref<boolean>(false)

const friend = ref<Friend>()
const getFriend = async () => {
    isSkeleton.value = true
    const result = await reqFriendDetailAPI(query.id as never)
    friend.value = result.data
    friend.value?.information.forEach((item) => {
        if (item.uid != userStore.profile.user?.uid) {
            isDisturb.value = item.is_disturb == 1 ? true : false
            isTop.value = item.is_top == 1 ? true : false
        }
    })
    isSkeleton.value = false
}
// --------------- 处理好友信息结束 ---------------



// --------------- 处理退出群聊开始 ---------------
const handleLogoutGroupChat = () => {
    if (admin.value?.uid == userStore.profile.user?.uid) {
        uni.showToast({
            title: '管理员退群,请先转让管理权限',
            duration: 1000,
            icon: 'none'
        })

        return false
    }

    uni.showModal({
        content: '确定要退出群聊吗?',
        confirmColor: global.THEME_COLOR,
        success: async (res) => {
            if (res.confirm) {
                await reqRemoveMemberAPI({gid: query.gid as never, uids: userStore.profile.user?.uid + ''})
                uni.showToast({
                    title: '退出群聊成功',
                    duration: 1000
                })

                setTimeout(() => {
                    goto('/pages/index/index')
                }, 1000)
            }
        }
	})
}
// --------------- 处理退出群聊结束 ---------------



// --------------- 处理解散群聊开始 ---------------
const handleDissolveGroupChat = () => {
    if (admin.value?.uid != userStore.profile.user?.uid) {
        uni.showToast({
            title: '管理员才能解散群聊',
            duration: 1000,
            icon: 'none'
        })

        return false
    }

    uni.showModal({
        content: '确定要解散群聊吗?',
        confirmColor: global.THEME_COLOR,
        success: async (res) => {
            if (res.confirm) {
                await reqDissolveAPI(groupChat.value.id, 'ws');
                uni.showToast({
                    title: '解散群聊成功',
                    duration: 1000
                })

                setTimeout(() => {
                    goto('/pages/index/index')
                }, 1000)
            }
        }
	})
}
// --------------- 处理解散群聊结束 ---------------



// --------------- 处理群聊信息开始 ---------------
// 管理员
const admin = ref<Member>()

// 群聊信息
const groupChat = ref<GroupChat>({
    id: 0,
    name: '',
    member: [],
    note: '',
    update_time: '',
    create_time: ''
})

// 获取群聊信息
const getGroupChatInfo = async () => {
    isSkeleton.value = true
    const result = await reqGroupChatDetailAPI(query.gid as never)
    groupChat.value = result.data
    groupChat.value.member.forEach((item: Member) => {
        // 判断免打扰 + 置顶
        if (item.uid == userStore.profile.user?.uid) {
            isDisturb.value = item.is_disturb == 1 ? true : false
            isTop.value = item.is_top == 1 ? true : false
        }

        // 判断是否群聊管理员
        if (item.is_admin == 1) {
            admin.value = item
        } else {
            // 转让管理员，候选成员列表
            candidateMemberList.value.push({
                uid: item.uid,
                username: item.username,
                avatar_url: item.avatar_url,
                mobile: item.mobile,
                is_admin: 0,
                is_disturb: 0,
                is_top: 0,
                is_check: false
            })
        }
    })
    isSkeleton.value = false
}
// --------------- 处理群聊信息结束 ---------------



// --------------- 处理编辑群名开始 ---------------
const popupNameRef = ref()

// 编辑参数
const editParams = ref<EditGroupChatParams>({
    id: query.gid as never,
    name: ''
})

// 编辑群名
const handleEditName = async () => {
    await reqEditGroupChatAPI(editParams.value)
    groupChat.value.name = editParams.value.name as never
    uni.showToast({
        title: '编辑群名成功',
        duration: 1000
    })

    popupNameRef.value.close()
}
// --------------- 处理编辑群名结束 ---------------



// --------------- 显示群二维码开始 ---------------
const popupQrcodeRef = ref()
const isHideQrcode = ref<boolean>(true)
const qrCodeText = ref('')

// 显示
const handleShowQrcode = () => {
    qrCodeText.value = 'sdfasfdf'
    isHideQrcode.value = false
    popupQrcodeRef.value.open('bottom')
}

// 关闭
const handleCloseQrcode = () => {
    isHideQrcode.value = true
    popupQrcodeRef.value.close()
}
// --------------- 显示群二维码结束 ---------------



// -------------- 转让管理员功能开始 --------------
const popupTransferRef = ref()

// 候选成员列表
const candidateMemberList = ref<Member[]>([])

// 选中的管理成员
const selectedMember = ref<Member>()

// 选择候选成员
const handleCheckMember = (member: Member) => {
    candidateMemberList.value.forEach((item: Member) => {
        item.is_admin = 0
    })

    member.is_admin = 1
    selectedMember.value = member
}

// 转让管理员
const handleConfirm = async () => {
    console.log('selectedMember = ', selectedMember.value);
    if (selectedMember.value?.uid == undefined) {
        uni.showToast({
            title: '请选择群聊成员',
            duration: 1000,
            icon: 'none'
        })
        
        return false
    }
    
    await reqTransferAdminAPI({gid: query.gid as never, member_id: selectedMember.value?.uid as never})
    groupChat.value.member.forEach((item: Member) => {
        if (item.uid == selectedMember.value?.uid) {
            item.is_admin = 1
        } else {
            item.is_admin = 0
        }
    })
    admin.value = {
        uid: selectedMember.value.uid,
        username: selectedMember.value.username,
        avatar_url: selectedMember.value.avatar_url,
        mobile: selectedMember.value.mobile,
        is_admin: 1,
        is_disturb: 0,
        is_top: 0,
        is_check: false
    }
    uni.showToast({
        title: '转让成功',
        duration: 1000
    })
    
    popupTransferRef.value.close()
}

// 取消
const handleCancel = () => {
    candidateMemberList.value.forEach((item: Member) => {
        item.is_admin = 0
    })
    popupTransferRef.value.close()
}
// -------------- 转让管理员功能结束 --------------



// ---------------- 免打扰功能开始 ----------------
const handleDisturb = async (value: any) => {
    if (query.mode == '1') { // 私聊
        await reqDisturbAPI({
            id: friend.value?.id as never,
            uid: friend.value?.uid == userStore.profile.user?.uid ? friend.value?.friend_id as never : friend.value?.uid as never,
            is_disturb: value.detail.value ? 1 : 0
        })
    } else { // 群聊
        await reqGroupChatDisturbAPI({
            id: groupChat.value?.id as never,
            uid: userStore.profile.user?.uid as never,
            is_disturb: value.detail.value ? 1 : 0
        })
    }

    isDisturb.value = value.detail.value
}
// ---------------- 免打扰功能结束 ----------------



// ----------------- 置顶功能开始 -----------------
const handleTop = async (value: any) => {
    if (query.mode == '1') { // 私聊
        await reqTopAPI({
            id: friend.value?.id as never,
            uid: friend.value?.uid == userStore.profile.user?.uid ? friend.value?.friend_id as never : friend.value?.uid as never,
            is_top: value.detail.value ? 1 : 0
        })
    } else { // 群聊
        await reqGroupChatTopAPI({
            id: groupChat.value?.id as never,
            uid: userStore.profile.user?.uid as never,
            is_top: value.detail.value ? 1 : 0
        })
    }

    isTop.value = value.detail.value
}
// ----------------- 置顶功能结束 -----------------
// --------------- 定义骨架变量开始 ---------------
// 定义是否显示骨架
const isSkeleton = ref(false)

// 定义骨架参数
const skeletons = reactive([{
  type: 'flex',
  num: 1,
  style: 'background-color: #fff;flex-direction: column;align-items: center;margin: 0 12rpx 20rpx 12rpx',
  children: [
    // 图片区域
    {
      type: 'custom',
      num: 1,
      style: 'width: 120rpx;height: 120rpx;border-radius: 10rpx;'
    },

    // 文本区域
    {
      type: 'custom',
      num: 1,
      style: ['width: 110rpx;height: 35rpx;margin-top: 10rpx;']
    }
  ]
}])
// --------------- 定义骨架变量结束 ---------------
</script>

<style scoped lang="scss">
.container {
    // 头部信息区域开始
    .user-wrap {
        padding: 20rpx 10rpx 0 10rpx;
        background-color: #fff;
        display: flex;
        flex-wrap: wrap;
        .item-box {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 110rpx;
            height: 160rpx;
            margin: 0 15rpx 20rpx 20rpx;

            // 头像区域开始
            .avatar {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 120rpx;
                height: 120rpx;
                border-radius: 10rpx;
                overflow: hidden;
                border: 2rpx solid #cdcdcd;
                image {
                    width: 110rpx;
                    height: 110rpx;
                }
            }
            // 头像区域结束

            // 用户名区域开始
            .username {
                margin-top: 8rpx;
                font-size: 24rpx;
                color: #cdcdcd;
            }
            // 用户名区域结束

            .top {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 120rpx;
                height: 120rpx;
                border-radius: 10rpx;
                overflow: hidden;
                border: 2rpx dashed #cdcdcd;
                margin-bottom: 36rpx;
                .icon-jia {
                    font-size: 60rpx;
                    color: #cdcdcd;
                }
                .icon-jian {
                    font-size: 60rpx;
                    color: #cdcdcd;
                }
            }
        }
    }
    // 头部信息区域结束

    // 群面板区域开始
    .group-wrap {
        margin-top: 20rpx;
    }

    // 查询聊天记录开始
    .search-record-wrap {
        margin-top: 20rpx;
    }

    // 操作区域开始
    .operate-wrap {
        margin-top: 20rpx;
        .operate-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #fff;
            padding: 30rpx;
            color: #000;
            border-bottom: 2rpx solid #f2f2f2;
            .left {
                font-size: 28rpx;
                flex: 1;
            }
        }
    }

    // 清空聊天记录开始
    .clear-record-wrap {
        margin-top: 20rpx;
    }

    // 投诉区域开始
    .complaint-wrap {
        margin-top: 20rpx;
    }

    // 退出群聊区域开始
    .btn-wrap {
        height: 100rpx;
        line-height: 100rpx;
        text-align: center;
        margin-top: 40rpx;
        background-color: #fff;
        color: red;
    }

    // 弹层区域开始
    .popup-wrap {
        padding-bottom: 40rpx;

        // 标题区域
        .title-box {
            display: flex;
            align-items: center;
            font-size: 32rpx;
            font-weight: bold;
            justify-content: center;
            height: 80rpx;
            color: $uni-color-primary;
            position: relative;
            border-bottom: 2rpx solid #e3e2e2;
            .icon-guanbi {
                font-size: 44rpx;
                color: #8e8c8c;
                position: absolute;
                right: 20rpx;
            }
        }

        // 输入框区域
        .input-box {
            padding: 30rpx 20rpx 0 20rpx;
        }

        // 二维码区域
        .qrcode-box {
            display: flex;
            justify-content: center;
            margin-top: 30rpx;
        }

        // 群聊成员区域
        .member-box {
            padding-top: 10rpx;
            height: 800rpx;
            overflow-y: scroll;
            .member {
                display: flex;
                align-items: center;
                border-bottom: 2rpx solid #f0f0f0;
                padding: 20rpx;
                .iconfont {
                    font-size: 50rpx;
                    color: #f0f0f0;
                }
                .icon-xuanzhong {
                    color: $uni-color-primary;
                }
                .avatar {
                    width: 120rpx;
                    height: 120rpx;
                    border: 2rpx solid #cdcdcd;

                    display: flex;
                    align-items: center;
                    justify-content: center;
                    border-radius: 10rpx;
                    margin: 0 20rpx;
                    image {
                        width: 110rpx;
                        height: 110rpx;
                    }
                }
                &:last-child {
                    border-bottom: none;
                }
            }
        }

        .member-btn-box {
            display: flex;
            justify-content: space-between;
            padding: 0rpx 100rpx;
            border-top: 2rpx solid #cdcdcd;
        }
    }
}
</style>